import {browse} from 'xe-utils'


/** @desc 打开页面方式 */
type TargetContext = '_self' | '_parent' | '_blank' | '_top';


/** @desc 新窗口打开页面 */
export const openWindow = (
    url: string,
    opts?: { target?: TargetContext; [key: string]: any }
) => {
    const {target = '_blank', ...others} = opts || {};
    window.open(
        url,
        target,
        Object.entries(others)
            .reduce((preValue: string[], curValue) => {
                const [key, value] = curValue;
                return [...preValue, `${key}=${value}`];
            }, [])
            .join(',')
    );
};

/** @desc 判断是否网络链接 */
export const regexUrl = new RegExp(
    '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
    'i'
);
/** @desc 是否是h5环境 */
export const isMobile = () => {
    return browse().isMobile
}

/** @desc 环境格式化时间  */

export function formatDate(time: number) {
    const date = new Date(time * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1，并用0填充
    const day = String(date.getDate()).padStart(2, '0'); // 用0填充
    const hours = String(date.getHours()).padStart(2, '0'); // 用0填充
    const minutes = String(date.getMinutes()).padStart(2, '0'); // 用0填充
    return `${year}-${month}-${day} ${hours}:${minutes}`;
}
/** @desc 格式化文件大小 */
export const formatFileSize = (fileSize: number) => {
    if (fileSize == null || fileSize === 0) {
        return '0 Bytes'
    }
    const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    let index = 0
    const srcSize = Number.parseFloat(fileSize.toString())
    index = Math.floor(Math.log(srcSize) / Math.log(1024))
    const size = srcSize / 1024 ** index
    return `${size.toFixed(2)} ${unitArr[index]}`
}

export default null;
